<template>
  <div class="search-container">
    <van-sticky>
       <form action="/">
        <van-search
          v-model.trim="searchText"
          show-action
          placeholder="请输入搜索关键词"
          background="#3296Fa"
          @search="onSearch"
          @cancel="$router.back()"
          @focus="isShoeResults = false"
        />
      </form>
    </van-sticky>

      <!-- 搜索结果 -->
      <ScarchResults v-if=" isShoeResults" :searchText="searchText"/>
      <!-- 搜索历史 -->
      <ScarchHistory @clear-history="history=[]" @search="onSearch" v-else-if="!searchText" :history="history"/>
      <!-- 联想建议 -->
      <ScarchSuggestion @clickItem="onSearch" :searchText="searchText" v-else/>

  </div>
</template>

<script>
import ScarchHistory from './components/scarch-history.vue'
import ScarchResults from './components/scarch-results.vue'
import ScarchSuggestion from './components/scarch-suggestion.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      searchText: '',
      isShoeResults: false,
      history: getItem('HMTT-HISTORY') || []
    }
  },
  components: {
    ScarchHistory,
    ScarchResults,
    ScarchSuggestion
  },
  watch: {
    history: {
      deep: true,
      handler () {
        setItem('HMTT-HISTORY', this.history)
      }
    }
  },
  created () {

  },

  methods: {
    // 敲回车或者点击搜索
    onSearch (val) {
      // 记录搜索历史
      this.history.unshift(val)
      // es6 新方法 可以实现数据去重
      this.history = [...new Set(this.history)]
      console.log(this.history)
      this.searchText = val
      this.isShoeResults = true
    }
  }
}
</script>

<style scoped lang='less'>
.search-container{
  .van-search__action{
    color: #fff;
  }
}
</style>
